package pers.jg.rrsserver.controller

import jakarta.servlet.http.HttpServletResponse
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.*


@RestController
@CrossOrigin
class FileCloudController {

    val rootPath: String = System.getenv("RRS_CLOUD_FILE_ROOT")

    @PostMapping("/api/postFile")
    fun postFile(
        @RequestParam("file") file: MultipartFile,
        @RequestParam("name") name: String,
        @RequestParam("path") path: String,
    ): String {
        if (file.isEmpty) {
            return ""
        }
        println(name)
        println(path)


        val uploadedFile = File("$rootPath/$path/$name")
        if (!uploadedFile.exists()) {
            File("$rootPath/$path").mkdirs()
        }
        try {
            file.transferTo(uploadedFile)
        } catch (e: Exception) {
            e.printStackTrace()
            return "Fail"
        }

        return "OK"
    }

    @GetMapping("/api/getFile")
    fun getFile(
        response: HttpServletResponse,
        @RequestParam("name") name: String,
        @RequestParam("path") path: String,
    ): String {

        // 若name或path为空，则返回空字符串
        if (name == "" || path == "") {
            return ""
        }

        val file = File("$rootPath/$path/$name")

        // 设置响应头信息、跨域信息等
        response.reset()
        response.contentType = "application/octet-stream"
        response.characterEncoding = "utf-8"
        response.setContentLength(file.length().toInt())
        response.setHeader("Content-Disposition", "attachment;filename=$name")
        response.setHeader("Access-Control-Allow-Origin", "*")

        // 开始传输文件流
        try {
            BufferedInputStream(FileInputStream(file)).use { bis ->
                val buff = ByteArray(1024)
                val os: OutputStream = response.outputStream
                var i: Int
                while ((bis.read(buff).also { i = it }) != -1) {
                    os.write(buff, 0, i)
                    os.flush()
                }
            }
        } catch (e: IOException) {
            return "下载失败"
        }
        return "下载成功"
    }

}